package com.lagou.util;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

public class MethodCollector {

    public Map<Long,Long> timeMap = new HashMap<>();

    public Long[] costSet = new Long[1000];

    //添加时间计数
    public void setTime(Long startTime,Long cost){
        int costInt = Math.toIntExact(cost);
        if(costInt>costSet.length){
            return;
        }
        if(costSet[costInt]==null){
            costSet[costInt] = 0L;
        }
        costSet[costInt] = costSet[costInt]+1;
        timeMap.put(startTime,cost);
    }

    //计算结果
    public Map<String,Long> getResult(){
        TreeMap<Long, Long> treeMap = new TreeMap<>(Comparator.naturalOrder());
        for (int i=0;i<100;i++) {
            if(costSet[i]!=null){
                treeMap.put(Long.valueOf(i),costSet[i]);
            }
        }
        TreeMap<Long, Long> transMap = new TreeMap<>(Comparator.naturalOrder());
        AtomicReference<Long> idx= new AtomicReference<>(0l);
        treeMap.forEach((key,value)->{
            transMap.put(idx.get(),key);
            idx.updateAndGet(v -> v + value);
        });

        Long total=treeMap.values().stream().mapToLong(o->o).sum();
        Double idx90= Math.ceil((double)total*90/100);
        Double idx99= Math.ceil((double)total*99/100);
        Map.Entry<Long, Long> idx90Entry = transMap.floorEntry(idx90.longValue());
        Map.Entry<Long, Long> idx99Entry = transMap.floorEntry(idx99.longValue());

        Long TP90=idx90Entry.getValue();
        Long TP99=idx99Entry.getValue();

        //System.out.println("TP90:"+TP90+", TP99:"+TP99);
        Map<String,Long> resMap = new HashMap<>();
        resMap.put("TP90",TP90);
        resMap.put("TP99",TP99);
        return resMap;
    }


    //清除一分钟以前的时间
    public void cleanOutTime(){
        for (Long startTime : timeMap.keySet()) {
            long diff = (new Date().getTime() - startTime)/1000;;
            if(diff>60){
                int s = Math.toIntExact(timeMap.get(startTime));
                costSet[s] = costSet[s]-1;
                timeMap.remove(startTime);
            }
        }
    }
}
